﻿using StartEAS_API.Utils;
using StartsEAS_API.Model;
using StartsEAS_API.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StartsEAS_API.DAL.CollegeD
{
    public class CollegeDAL
    {
        private readonly StarsEASContext _context;
        public CollegeDAL(StarsEASContext context) { 
            _context = context;
        }

        public ResultUtils GetAllCollege() {
            StarsEASContext _context = new StarsEASContext();
            List<College> collegeList = _context.Colleges.ToList();
            AppLog.WriteInfo($"查询学院信息---查询到{collegeList.Count()}条学院信息", true);
            return new ResultUtils() { code = 200, message = collegeList };
        }

        public ResultUtils GetCollege(int CollegeId){
            StarsEASContext _context = new StarsEASContext();
            College college = _context.Colleges.FirstOrDefault(o => o.CollegeId == CollegeId);
            AppLog.WriteInfo($"查询学院信息---查询{CollegeId}学院信息", true);
            return new ResultUtils() { code = 200, message = college };
        }

        public ResultUtils InsertCollege(string CollegeName) {
            StarsEASContext _context = new StarsEASContext();
            if (CollegeName == null)
            {
                AppLog.WriteError($"新增学院信息---学院名称为空", true);
                return new ResultUtils() { code = 500, message = "请输入您的学院名称" };
            }
            College college = new College() {CollegeId=0, CollegeName=CollegeName};
            _context.Colleges.Add(college);
            int result = _context.SaveChanges();
            if (result == 0) {
                AppLog.WriteError($"新增学院信息---新增学院{CollegeName}失败", true);
                return new ResultUtils() { code = 500, message = "新增失败" };
            }
            AppLog.WriteInfo($"新增学院信息---新增学院{CollegeName}成功", true);
            return new ResultUtils() { code=200,message= result };
        }

        public ResultUtils UpdateCollege(College data) {
            StarsEASContext _context = new StarsEASContext();
            if (data == null)
            {
                AppLog.WriteInfo($"修改学院信息---未传入学院信息值", true);
                return new ResultUtils() { code = 500, message = "请传入新的学院信息" };
            }
            College college = _context.Colleges.FirstOrDefault(o => o.CollegeId == data.CollegeId);
            if (college == null) {
                AppLog.WriteError($"修改学院信息---未查询到学院编号{data.CollegeId}的学院", true);
                return new ResultUtils() { code = 500, message = "学院编号错误" };
            }
            college.CollegeName = data.CollegeName;
            int result = _context.SaveChanges();
            if (result == 0) {
                AppLog.WriteError($"修改学院信息---学院编号{data.CollegeId}信息修改失败", true);
                return new ResultUtils() { code = 500, message = "修改失败" };
            }
            return new ResultUtils() { code = 200, message = "修改成功" };
        }

    }
}
